package com.tucy.logistics.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.tucy.logistics.common.constants.RedisConstants;
import com.tucy.logistics.common.constants.SecurityConstants;
import com.tucy.logistics.common.entity.user.SystemUser;
import com.tucy.logistics.security.service.SystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * author: tcy
 * createDate: 2023/7/10
 * description: 登录信息工具类
 */
@Configuration
public class LoginInfoUtil {

    private static RedisUtil redisUtil;

    private static SystemUserService systemUserService;

    @Autowired(required = false)
    public void setRedisService(@Autowired RedisUtil redisUtil) {
        LoginInfoUtil.redisUtil = redisUtil;
    }

    @Autowired(required = false)
    public void setSystemUserService(@Autowired SystemUserService systemUserService) {
        LoginInfoUtil.systemUserService = systemUserService;
    }

    public LoginInfoUtil() {
    }

    public static JSONObject getJwtPayload() {
        try {
            String token = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("authorization");
            if (StrUtil.isBlank(token)) {
                return new JSONObject();
            }

            Object userId = redisUtil.get(RedisConstants.login_token + token);
            if (ObjectUtil.isEmpty(userId)) {
                return new JSONObject();
            }

            Object userInfo = redisUtil.get(RedisConstants.login_info + userId);
            if(ObjectUtil.isNotEmpty(userInfo)) {
                return JSONUtil.parseObj(userInfo);
            } else {
                SystemUser systemUser = systemUserService.queryUserById(userId.toString());
                JSONObject jsonObject = new JSONObject();
                jsonObject.set(SecurityConstants.DETAILS_USERID,systemUser.getId());
                jsonObject.set(SecurityConstants.DETAILS_USERNAME,systemUser.getUsername());
                jsonObject.set(SecurityConstants.DETAILS_NICKNAME,systemUser.getNickname());
                jsonObject.set(SecurityConstants.MOBILE,systemUser.getMobile());
                jsonObject.set(SecurityConstants.OPENID,systemUser.getOpenId());
                jsonObject.set(SecurityConstants.ROLEID,systemUser.getRoleId());

                redisUtil.set(RedisConstants.login_info + userId, jsonObject,36000);
                return jsonObject;
            }
        } catch (Exception e) {
            return new JSONObject();
        }
    }

    public static Long getUserId() {
        Long id = getJwtPayload().getLong(SecurityConstants.DETAILS_USERID);
        return id == null ? 0L : id;
    }

    public static String getUsername() {
        String username = getJwtPayload().getStr(SecurityConstants.DETAILS_USERNAME);
        return StrUtil.isBlank(username) ? "用户名不存在" : username;
    }

    public static String getOpenId() {
        String openid = getJwtPayload().getStr(SecurityConstants.OPENID);
        return StrUtil.isBlank(openid) ? "openid不存在" : openid;
    }

    public static String getMobile() {
        String mobile = getJwtPayload().getStr(SecurityConstants.MOBILE);
        return StrUtil.isBlank(mobile) ? "mobile不存在" : mobile;
    }

    public static String getChineseName() {
        String name = getJwtPayload().getStr(SecurityConstants.DETAILS_NICKNAME);
        return StrUtil.isBlank(name) ? "name不存在" : name;
    }

    public static String getRoleId() {
        String roleId = getJwtPayload().getStr(SecurityConstants.ROLEID);
        return StrUtil.isBlank(roleId) ? "roleId不存在" : roleId;
    }

    public static String getIpAddress() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip)  || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            return ip;
        } catch (Exception e) {
            return null;
        }
    }

}
